package com.fingard.dsp.bank.directbank.spdb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBatchOpenBill;
import com.fingard.dsp.bank.reqrespobj.batchbill.*;
import com.fingard.dsp.bank.reqrespobj.batchbill.detail.RetAtsBatOpenBillSubmitQryDetail;
import com.fingard.dsp.bank.reqrespobj.batchbill.detail.RetAtsBillAddCancelSubmit;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.util.*;

/**
 * Created by F on 2019/10/22.
 */
public class SPDB01BatchOpenBill extends SPDB01Base implements IBatchOpenBill {
    @Override
    public RetAtsBatchQry batchQry(ReqBatchQry query) throws Exception {
        return null;
    }

    @Override
    public RetAtsBatchInfoQry batchInfoQry(ReqBatchInfoQry query) throws Exception {
        return null;
    }

    @Override
    public RetAtsBatchAddSubmit batchAddSubmit(ReqBatchAddSubmit query) throws Exception {
        return null;
    }

    @Override
    public RetAtsBatchModSubmit batchModSubmit(ReqBatchModSubmit query) throws Exception {
        return null;
    }

    @Override
    public RetAtsBatchDelSubmit batchDelSubmit(ReqBatchDelSubmit query) throws Exception {
        return null;
    }

    @Override
    public RetAtsBatchSubmitApply batchSubmitApply(ReqBatchSubmitApply query) throws Exception {
        return null;
    }

    @Override
    public RetAtsBatchSubmitCancel batchSubmitCancel(ReqBatchSubmitCancel query) throws Exception {
        return null;
    }

    @Override
    public RetAtsBillAddSubmit billAddSubmit(ReqBillAddSubmit query) throws Exception {
        return null;
    }

    @Override
    public RetAtsBillAddCancelSubmit billAddCancelSubmit(ReqBillAddCancelSubmit query) throws Exception {
        return null;
    }

    @Override
    public RetAtsBatOpenBillSubmit BatOpenBillSubmit(ReqBatOpenBillSubmit query) throws Exception {

        RetAtsBatOpenBillSubmit retAts = new RetAtsBatOpenBillSubmit(query.reqHeader);
        StringBuilder sequenceNoData  = new StringBuilder();
            SPDB01Header header = new SPDB01Header();
            header.transCode ="EE02";
            try {
                XmlTextWriter xmlTextWriter = new XmlTextWriter();
                xmlTextWriter.writeStartElement("body");
//                transMasterID
                xmlTextWriter.writeElementString("transMasterID",bankFront.org);
                xmlTextWriter.writeElementString("totalNumber",String.format("%4s",query.totalNum));//总笔数,长度4
                xmlTextWriter.writeElementString("totalAmount",String.format("%13s",query.totalAmount));//总金额，申请承兑金额
                String acceptanceType;
                if("1".equals(query.accpSameBnk)){
                    acceptanceType ="00";//行内
                }else{
                    acceptanceType="01";//行外
                }
                xmlTextWriter.writeElementString("acceptanceType",acceptanceType);//行内行外标识
                String eBillType = query.billType;
                String eDraweringTxType;
                if("01".equals(acceptanceType)){
                    eDraweringTxType = "01";
                    if("1".equals(eBillType)){
                        eBillType ="AC01";
                    }else{

                    }
                }else if("1".equals(eBillType)){
                    //银票
                    eBillType ="AC01";
//                throw new Exception("承兑人为同行的银承只能发起自动承兑和自动提示收票");
                  eDraweringTxType = "02";//自动提示承兑
                }else if("2".equals(eBillType)){
                    //商票
                    eBillType ="AC02";
                    eDraweringTxType = "01";
                }else {
                    throw new Exception("票据类型异常："+eBillType);
                }
                xmlTextWriter.writeElementString("eDraweringTxType",eDraweringTxType);//交易类型
                xmlTextWriter.writeElementString("eBillType",eBillType);//票据类型
                xmlTextWriter.writeElementString("eDrawerType","RC01");//出票人类型(4)
                xmlTextWriter.writeElementString("acctNo",String.format("%-32s",query.drawAct));//出票人账户(32)
//                xmlTextWriter.writeElementString("eDrawerBankNo",query.detail.drawBnkCode);
                if("AC01".equals(eBillType)){
                    String summaryEBillFlag  = "02";//是
                    xmlTextWriter.writeElementString("summaryEBillFlag",summaryEBillFlag);//是否按票据到期日汇总回单(2)
                    xmlTextWriter.writeElementString("discountingEBillFlag","");//是否申请保贴(2)

                }else{
                    String discountingEBillFlag  ="02";//否
                    xmlTextWriter.writeElementString("summaryEBillFlag","");//是否按票据到期日汇总回单(2)
                    xmlTextWriter.writeElementString("discountingEBillFlag",discountingEBillFlag);//是否申请保贴(2)
                }
                xmlTextWriter.writeElementString("bargainNo",String.format("%-30s",query.bargainNo));//合同编号(30)
                xmlTextWriter.writeElementString("invoiceNo",String.format("%-30s",query.invoiceNo));//发票号码(30)
                xmlTextWriter.writeElementString("remark","");//备注
//                movieNo	影像流水号	FixString(30)	N
                xmlTextWriter.writeElementString("movieNo","");
                xmlTextWriter.writeStartElementByAttr("lists", "<lists name=\"edraftList\">");
                int sequenceNo = 0;
                while (query.readRecord()) {
                    String seqNoStr = String.format("%04d",++sequenceNo);
                    sequenceNoData.append(seqNoStr+"_"+query.detail.postScript+"\r\n");
                    xmlTextWriter.writeStartElement("list");
//            <sequenceNo></sequenceNo>
                    xmlTextWriter.writeElementString("sequenceNo", seqNoStr);//序号(4)
//            <billNo></billNo>
                    xmlTextWriter.writeElementString("billNo", "");//电子票号(30)n
//            <voteDate></voteDate>
                    xmlTextWriter.writeElementString("voteDate", DateHelper.convertD10toD8(query.detail.issDate));//出票日(8)
//            <expiryDate></expiryDate>
                    xmlTextWriter.writeElementString("expiryDate", DateHelper.convertD10toD8(query.detail.dueDate));//到期日(8)
                    if ("AC02".equals(eBillType)) {
//            <acceptorName></acceptorName>
                        xmlTextWriter.writeElementString("acceptorName", String.format("%-62s", query.detail.accpName)); //承兑人名称(62)
//            <acceptorAcctNo></acceptorAcctNo>
                        xmlTextWriter.writeElementString("acceptorAcctNo", String.format("%-32s", query.detail.accpAct));//承兑人账号(32)
//            <acceptorBankNo></acceptorBankNo>
                        xmlTextWriter.writeElementString("acceptorBankNo", String.format("%-12s", query.detail.accpBnkCode));//承兑人行号(12)
                    }
//            <eBillAmount></eBillAmount>
                    xmlTextWriter.writeElementString("eBillAmount", String.format("%13s", query.detail.billAmt));//申请承兑金额
//            <canTransferFlag></canTransferFlag>
                    if ("1".equals(query.detail.transFlag)) {
                        xmlTextWriter.writeElementString("canTransferFlag", "EM00");//转让
                    } else {
                        xmlTextWriter.writeElementString("canTransferFlag", "EM01");//
                    }
//            <ePayeeAcctName></ePayeeAcctName>
                    xmlTextWriter.writeElementString("ePayeeAcctName", String.format("%-62s", query.detail.payeeName));//收款人名称(62)
//            <ePayeeAcctNo></ePayeeAcctNo>
                    xmlTextWriter.writeElementString("ePayeeAcctNo", String.format("%-32s", query.detail.payeeAct));//收款人开户账户(32)
//            <ePayeeBankNo></ePayeeBankNo>
                    xmlTextWriter.writeElementString("ePayeeBankNo", String.format("%-12s", query.detail.payeeBnkCode));//收款人开户行行号(12)
//                    bargOneNo	合同编号	FixString(30)	N
                    xmlTextWriter.writeElementString("bargOneNo",query.detail.contractNo);
//            </list>
                    xmlTextWriter.writeEndElement();
                }
                xmlTextWriter.writeEndDocument();
                String[] result = sendToBank(xmlTextWriter.toXmlString(), header);
                if (result[0].length() == 0) {
                    StringBuilder tmpbkMsg = new StringBuilder();
                    XmlTextReader tmpbkReader = loadBankRespXmlReader(result[1], tmpbkMsg);
                    if (tmpbkReader != null) {
                        String returnCode = tmpbkReader.getFirstText("/packet/head/returnCode");
                        if (returnCode != null && "AAAAAAA".equals(returnCode)) {
                            retAts.respCode = "0";
                            retAts.transState = returnCode;
                            retAts.payInfoCode = returnCode;
                            String businessId = tmpbkReader.getFirstText("/packet/body/businessId");
                            retAts.reqSeqID = query.reqBatchNo;
                            retAts.bnkBusiNo = businessId;
                        } else {
                            retAts.respCode = "0";
                            retAts.transState = returnCode;
                            retAts.payInfoCode = returnCode;
                            retAts.respInfo = tmpbkReader.getFirstText("/packet/body/returnMsg");
                            String businessId = tmpbkReader.getFirstText("/packet/body/businessId");
                            retAts.reqSeqID = query.reqBatchNo;
                            retAts.bnkBusiNo = businessId;
                        }
                        String filename =getBankConfig().getValueAsString("eBillBatchNoDir")+ File.separator+Format.Date6YearMonth.format(new Date())+File.separator+  query.reqBatchNo+".txt";
                        FileHelper.writeFile(filename,sequenceNoData.toString(),getCharset());
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpbkMsg.toString();
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = result[1];
                }
            } catch (Exception e) {
                retAts.respCode = "-1";
                retAts.respInfo = e.getMessage();
                e.printStackTrace();
            }
        retAts.writeAfterDetail();
        return retAts;
    }

    @Override
    public RetAtsBatOpenBillSubmitQry BatOpenBillSubmitQry(ReqBatOpenBillSubmitQry query) throws Exception {
        RetAtsBatOpenBillSubmitQry retAts = new RetAtsBatOpenBillSubmitQry(query.reqHeader);
        query.readRecord();
        int totalNum = -1;
        int queryStartNum = 1;
        int hadQueryNum = 0;

        try {
            Map<String,String> sequenceNoMap = new HashMap<String, String>();
            String filename =getBankConfig().getValueAsString("eBillBatchNoDir")+ File.separator+query.detail.operateDate.substring(0, 4) + query.detail.operateDate.substring(5, 7)+ File.separator+query.detail.reqSeqID +".txt";
            if(!FileHelper.existFile(filename)){
                throw new Exception("批次序号文件：【"+filename+"】不存在，请检查");
            }
            String sequenceNoData = FileHelper.readFileText(filename,getCharset());
            if(StringHelper.isNullOrEmpty(sequenceNoData)){
                throw new Exception("批次序号文件：【"+filename+"】异常，请检查");
            }
            String[] sequenceNoArr = sequenceNoData.split("\\r\\n");
            if(sequenceNoArr==null||sequenceNoArr.length==0){
                throw new Exception("批次序号文件：【"+filename+"】异常，请检查");
            }else {
                for(String sequenceNoitem :sequenceNoArr){
                    String[] sequenceNoInfo =sequenceNoitem.split("_");
                    sequenceNoMap.put(sequenceNoInfo[0],sequenceNoInfo[1]);
                }
            }
            do {
                XmlTextWriter xmlTextWriter = new XmlTextWriter();
                SPDB01Header header = new SPDB01Header();
                header.transCode = "EE28";
                xmlTextWriter.writeStartElement("body");
//        transMasterID	交易客户号	FixString(10)	N	若输入则查询该客户号下的数据，若未输入则查询报文头客户号的数据
                xmlTextWriter.writeElementString("transMasterID", bankFront.org);
//        eBillBatchNo	批次号	FixString(18)	Y
                xmlTextWriter.writeElementString("eBillBatchNo", DateHelper.convertD10toD8(query.detail.operateDate.substring(0, 10)) + query.detail.bnkBusiNo);
//        businessType	查询类别	FixString(2)	N	01-请求中 02-审批同意
                xmlTextWriter.writeElementString("businessType", "");
//        beginNumber	起始记录数	FixNumber(4)	Y	最小为1
//        xmlTextWriter.writeElementString("beginNumber",String.format("%4s","1"));
                xmlTextWriter.writeElementString("beginNumber", queryStartNum + "");
//        queryNumber	查询记录数	FixNumber(4)	Y	最大为20
//        xmlTextWriter.writeElementString("queryNumber",String.format("%4s","1"));
                xmlTextWriter.writeElementString("queryNumber", "20");
                xmlTextWriter.writeEndDocument();
                String[] result = sendToBank(xmlTextWriter.toXmlString(), header);
                if (result[0].length() == 0) {
                    StringBuilder tmpsbMsg = new StringBuilder();
                    XmlTextReader tmpbkReader = loadBankRespXmlReader(result[1], tmpsbMsg);
                    if (tmpbkReader != null) {
                        String returnCode = tmpbkReader.getFirstText("/packet/head/returnCode");
                        if (StringHelper.hasAnyChar(returnCode) && "AAAAAAA".equals(returnCode)) {
                            String totalNumber = tmpbkReader.getFirstText("/packet/body/totalNumber").trim();
                            if (StringHelper.hasAnyChar(totalNumber) && totalNum == -1) {
                                totalNum = Integer.valueOf(totalNumber);
                                retAts.respCode = "0";
                                retAts.respInfo = "查询成功";
                                retAts.reqSeqID = query.detail.reqSeqID;
                                retAts.transState = returnCode;
                                retAts.payInfoCode = returnCode;
                            }
                            while(tmpbkReader.read("/packet/body/lists/list")) {
                                hadQueryNum++;
                                queryStartNum++;
                                RetAtsBatOpenBillSubmitQryDetail detail = new RetAtsBatOpenBillSubmitQryDetail();
                                detail.respCode = "0";
                                detail.respInfo = "";
//                        detail.reqSeqID =map.get("REQSEQID").toString();
//                        00-未处理  01-处理成功  02-处理失败 03 已发送 04-处理中 05-银行审核中 06-被银行拒绝
                                detail.result = tmpbkReader.readedXElement.getSingleText("status");
                                if ("01".equals(detail.result)) {
                                    String billNo = tmpbkReader.readedXElement.getSingleText("billNo");
                                    detail.billNo = "-".equals(billNo) ? "" : billNo;
                                    String billStatus = tmpbkReader.readedXElement.getSingleText("eBillStatus");
                                    detail.billState = "-".equals(billStatus) ? "" : billStatus;
                                    if ((StringHelper.isNullOrEmpty(detail.billNo) || StringHelper.isNullOrEmpty(detail.billState)) && "01".equals(detail.result)) {
                                        detail.result = "00";
                                    }
                                }
                                String key = tmpbkReader.readedXElement.getSingleText("seqNo");
                                detail.postScript = sequenceNoMap.get(key);
                                detail.payInfoCode = detail.result;
                                retAts.writeRetDetail(detail);
                            }
                        } else {
                            throw new Exception(tmpbkReader.getFirstText("/packet/body/returnMsg").trim());
                        }
                    } else {
                        throw new Exception(tmpsbMsg.toString());
                    }
                } else {
                    throw new Exception(result[1]);
                }
            } while (hadQueryNum < totalNum);

        } catch (Exception e) {
            retAts = new RetAtsBatOpenBillSubmitQry(reqHeader);
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            retAts.writeBeforeDetail();
            e.printStackTrace();
        }
        retAts.writeAfterDetail();
        return retAts;
    }



    @Override
    public RetAtsOrgQry orgQry(ReqOrgQry reqOrgQry) throws Exception {
        return null;
    }


}
